package cn.e3mall.sso.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.utils.E3Result;
import cn.e3mall.common.utils.JsonUtils;
import cn.e3mall.mapper.TbUserMapper;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.pojo.TbUserExample;
import cn.e3mall.pojo.TbUserExample.Criteria;
import cn.e3mall.sso.service.RegisterService;

@Service
public class RegisterServiceImpl implements RegisterService {
	
	@Autowired
	private TbUserMapper userMapper;
	
	//校验数据是否与数据库重复
	@Override
	public E3Result checkUserData(String data, Integer type) {
		TbUserExample example = new TbUserExample();
		
		Criteria criteria = example.createCriteria();
		
		//判断数据类型生成不同的查询条件 : 1.用户名 2.手机号 3.邮箱
		if(type == 1) {
			criteria.andUsernameEqualTo(data);
		}else if(type == 2) {
			criteria.andPhoneEqualTo(data);
		}else if(type == 3) {
			criteria.andEmailEqualTo(data);
		}else {
			return E3Result.build(400,"数据类型错误");
		}
		
		//执行查询返回结果
		List<TbUser> list = userMapper.selectByExample(example);
		
		//若不为空返回false
		if(list != null && list.size() > 0)	return E3Result.ok(false);
		
		//为空返回true
		return E3Result.ok(true);
	}

	/**
	 * 	用户注册
	 */
	@Override
	public E3Result regist(TbUser user) {
		/**
		 * 	1.有效性校验
		 * 		>校验字段是否为空
		 * 		>校验字段是否重复
		 * 	2.补全信息
		 * 	3.md5加密
		 * 	4.插入数据
		 * 	5.返回结果
		 */
		String username = user.getUsername();
		String password = user.getPassword();
		String phone = user.getPhone();
		
		//校验字段是否为空
		if(StringUtils.isBlank(username) || StringUtils.isBlank(username) 
				|| StringUtils.isBlank(username))
			return E3Result.build(400, "数据不能为空");
		//校验字段是否重复
		
		E3Result userResult = checkUserData(username,1);
		//若用户字段重复
		if(!(boolean) userResult.getData()) return E3Result.build(400, "用户名重复");
			
		E3Result phoneResult = checkUserData(phone,2);
		//若手机字段重复
		if(!(boolean) phoneResult.getData()) return E3Result.build(400, "手机号重复");
		
		//md5加密
		String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
		
		//补全信息
		user.setPassword(md5Password);
		user.setUpdated(new Date());
		user.setCreated(new Date());
		
		//插入数据
		userMapper.insert(user);
		
		return E3Result.ok();
	}


}
